package cn.com.open.ms.ecgpaasdatarest.interceptor;

import cn.com.open.ms.ecgpaasdatarest.common.Constant;
import cn.com.open.ms.ecgpaasdatarest.common.Result;
import cn.com.open.ms.ecgpaasdatarest.dynamicconfig.DBContextHolder;
import cn.com.open.ms.ecgpaasdatarest.service.AppService;
import cn.com.open.ms.ecgpaasdatarest.utils.HtmlUtil;
import cn.com.open.ms.ecgpaasdatarest.utils.Md5;
import cn.com.open.ms.ecgpaasdatarest.utils.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;


/**
 * 验签拦截器
 */
public class VerifySignatureInterceptor implements HandlerInterceptor {

    @Autowired
    private AppService appService;
    @Value("${verifySignature.onOff}")
    private String onOff;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //开关
        if (Constant.ON.equals(onOff)) {
            String appKey = request.getHeader("appKey");
            String timestamp = request.getHeader("timestamp");
            String signatureNonce = request.getHeader("signatureNonce");
            String platform = request.getHeader("platform");
            String signature = request.getHeader("signature");
            String requestURI = request.getRequestURI();

            //存在空参数
            if (!ParamUtil.paramMandatoryCheck(Arrays.asList(appKey, timestamp, signature, signatureNonce, platform))) {
                HtmlUtil.writeJson(response, new Result("请求头信息不完整！",System.currentTimeMillis(),null),HttpStatus.UNAUTHORIZED);
                return false;
            }
            //查询AppKey是否有效 + 数据鉴权
            DBContextHolder.setDbType("default");
            String[] split = requestURI.substring(1).split("\\/");
            String businessName = split[2];
            String tableName = split[3];
            if(!ParamUtil.paramMandatoryCheck(Arrays.asList(businessName,tableName))){
                HtmlUtil.writeJson(response, new Result("请求参数不完整！",System.currentTimeMillis(),null),HttpStatus.UNAUTHORIZED);
                return false;
            }
            String appSecret = appService.findAppSecretByAppKey(appKey,businessName,tableName);
            if (appSecret == null) {
                HtmlUtil.writeJson(response, new Result("当前AppKey无数据访问权限！",System.currentTimeMillis(),null),HttpStatus.UNAUTHORIZED);
                return false;
            }
            //校验当前appSecret
            if (!verifySignature(timestamp, signatureNonce, platform, appSecret, signature)) {
                HtmlUtil.writeJson(response, new Result("当前AppSecret校验失败！",System.currentTimeMillis(),null),HttpStatus.UNAUTHORIZED);
                return false;
            }
        }
        return true;
    }

    /**
     * 校验签名
     */
    private boolean verifySignature(String timestamp, String signatureNonce, String platform, String appSecret, String signature) {
        String str = String.format("timestamp=%s&signatureNonce=%s&platform=%s&appSecret=%s", timestamp, signatureNonce, platform, appSecret);
        return signature.equals(Md5.md5(str));
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //do nothing
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //do nothing
    }

    public static void main(String[] args) {
        String timestamp = "123123123";
        String signatureNonce = "234234";
        String platform = "1";
        String appSecret = "b6416242678e4d2181b0a02320367051";

        String str = String.format("timestamp=%s&signatureNonce=%s&platform=%s&appSecret=%s", timestamp, signatureNonce, platform, appSecret);
        System.out.println((Md5.md5(str)));
    }

}

